package com.infoguia;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.infoguia.db.InfoguiaDao;
import com.infoguia.to.CategoryTo;
import com.infoguia.to.CompanyTo;
import com.infoguia.to.PhoneTo;
import com.infoguia.util.Constants;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.OnHierarchyChangeListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class ResultList extends ListActivity {

	private static final int ACTIVITY_CATEGORY_DETAIL = 2;
	private static final int ACTIVITY_DETAIL_ITEM = 3;
	private String mail;
	private String phone;
	private InfoguiaDao dao;
	private Long srecom;
	private Long mRowId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.resultlist);

		try {
			Bundle extras = getIntent().getExtras();
			mRowId = extras != null ? extras.getLong(Constants.ID) : null;
			srecom = extras != null ? extras.getLong("SEARCH_REC") : null;

			if (mRowId != null) {
				this.loadResult(mRowId);
			}
			this.goHome();

		} catch (Exception e) {
			System.err.println(e);
		}
		
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent i = new Intent(this, DetailItem.class);
		i.putExtra(Constants.ID, id);
		TextView text = (TextView) v.findViewWithTag("idCom");
		DetailItem.ID_COMPANY = text.getText().toString().trim();
		startActivityForResult(i, ACTIVITY_CATEGORY_DETAIL);
	}

	private void loadResult(Long index) throws IOException {

		List<CategoryTo> search;
		List<CompanyTo> companies;
		CategoryTo category;
		String strTemp;

		if (dao == null) {
			dao = new InfoguiaDao(this);
			dao.open();
		}

		category = new CategoryTo();
		if (srecom != null && srecom == 1) {
			category = dao.getCategoryFull(index);
		} else {
			if (SearchResults.STATE_SEARCH == 0) {
				search = dao.getCategoryByName(SearchResults.STR_SEARCH);
			} else {
				search = dao.getCategoryByState(SearchResults.STR_SEARCH,
						SearchResults.STATE_SEARCH);
			}

			category = search.get(index.intValue());
		}

		companies = category.getCompany();

		TextView headerResultList = (TextView) findViewById(R.id.headerResultList);
		headerResultList.setText(category.getName());

		String[] from = new String[] { "row_0", "row_1", "row_2", "row_3" };
		int[] to = new int[] { R.id.idCom, R.id.nameCom, R.id.dirCom,
				R.id.telDetail };
		List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();

		for (CompanyTo cat : companies) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("row_0", cat.getId());
			map.put("row_1", cat.getName());
			map.put("row_2", cat.getAddress());

			strTemp = "";
			if (cat.getNumbers() != null) {
				for (PhoneTo phone : cat.getNumbers()) {
					strTemp += "\t" + phone.getCode() + "-" + phone.getNumber()
							+ "\n";
				}
			}
			map.put("row_3", strTemp);

			fillMaps.add(map);
		}

		setListAdapter(new SimpleAdapter(this, fillMaps, R.layout.rl_row, from,
				to));

		OnHierarchyChangeListener listener = new OnHierarchyChangeListener() {
			
			@Override
			public void onChildViewRemoved(View parent, View child) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onChildViewAdded(View parent, View child) {
								
				TextView text = (TextView) child.findViewWithTag("idCom");
				DetailItem.ID_COMPANY = text.getText().toString().trim();

				if (dao == null) {
					dao = new InfoguiaDao(ResultList.this);
					dao.open();
				}

				CompanyTo company = dao.getCompany(Long
						.parseLong(DetailItem.ID_COMPANY));
				mail = company.getMail();		
				phone = company.getNumbers().get(0).getCode() + "" + company.getNumbers().get(0).getNumber();
				
				ImageView btnSend = (ImageView) child.findViewById(R.id.mail2);
				btnSend.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent i = new Intent(ResultList.this, Mail.class);
						i.putExtra(Constants.MAIL_TO, mail);
						i.putExtra(Constants.LAYOUT_ID, R.layout.resultlist);
						i.putExtra("STR_SEARCH", SearchResults.STR_SEARCH);
						i.putExtra("STATE_SEARCH", SearchResults.STATE_SEARCH);
						i.putExtra("mRowId", mRowId);
						i.putExtra("SEARCH_REC", srecom);						
						startActivityForResult(i, ACTIVITY_DETAIL_ITEM);
					}
				});
				
				btnSend = (ImageView) child.findViewById(R.id.phone);
				btnSend.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent callIntent = new Intent(Intent.ACTION_DIAL, Uri
								.parse("tel:"+phone));
						startActivity(callIntent);
					}
				});
				
				dao.close();
				dao = null;
			}
		};
		
		getListView().setOnHierarchyChangeListener(listener);
	}
	
	public void goHome() {

		ImageView home = (ImageView) findViewById(R.id.home);

		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(ResultList.this, StartActivity.class);
				startActivityForResult(i, 1);
			}
		});

	}
}
